package tech.wangpai.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tech.wangpai.domain.User;
import tech.wangpai.service.UserService;

@RestController
public class UserController {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserService userService;

    @GetMapping(value = "/users", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity queryUser(String username) {
        logger.info("调用/users");
        return new ResponseEntity(userService.queryUser(username), HttpStatus.OK);
    }

    @GetMapping(value = "/user/{userId}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity getUserById(@PathVariable(value = "userId") String userId) {
        return new ResponseEntity(userService.getUserById(userId), HttpStatus.OK);
    }

    @PostMapping(value = "/user", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity addUser(@RequestBody User user) {
        userService.addUser(user);
        return new ResponseEntity(HttpStatus.OK);
    }

    @DeleteMapping(value = "/user/{userId}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity deleteUserById(@PathVariable(value = "userId") String userId) {
        userService.delUserById(userId);
        return new ResponseEntity(HttpStatus.OK);
    }

    @PutMapping(value = "/user/{userId}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity updateUserById(@PathVariable(value = "userId") String userId, @RequestBody User user) {
        userService.updateUserById(userId, user);
        return new ResponseEntity(HttpStatus.OK);
    }

    @PatchMapping(value = "/user/{userId}/{age}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity updateUserAgeById(@PathVariable(value = "userId") String userId, @PathVariable(value = "age") Integer age) {
        userService.updateUserAgeById(userId, age);
        return new ResponseEntity(HttpStatus.OK);
    }

}
